<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdapterWebController;
use App\Models\Agent\Software;
use App\Models\Sale\Sale;
use App\Modules\Agent\Agent;
use Illuminate\Http\Request;
//use App\AgentExport;
use Excel;

class AgentController extends AdapterWebController
{

    /**
     * 添加代理
     */
    public function addAgent(Request $request)
    {
        if($request->isMethod('get')){
            $saleModel = new Sale();
            $saleList = $saleModel->get();
            if(!empty($saleList)){
                $saleList = $saleList->toArray();
            }
            return view('admin.agent.add_agent',['user'=>1,'addAgentStatus'=>1,'client'=>1, 'saleList' => $saleList]);
        }

        $file1Res = $this->fileUpload($request, 'protocol_file');
        if (!$file1Res['status']) {
            throw_exception('请上传协议备案');
        }
        $file2Res = $this->fileUpload($request,'record_file');

        if (!$file2Res['status']) {
            $this->delFileByPath($file1Res['url']);
            throw_exception('请上传档案备案');
        }

        $postData = array_filter($request->all());
        $postData['protocol_file'] = $file1Res['url'];
        $postData['record_file'] = $file2Res['url'];
        $res = $this->appLayerExec(Agent::class, 'addAgent', $postData);
        if ($res['status'] != 1) {
            $this->delFileByPath($file1Res['url']);
            $this->delFileByPath($file2Res['url']);
            return '添加错误';
        }
        return view('admin.jump')->with([
            'message'=>'提交成功！',
            'url' =>'http://'.$_SERVER['HTTP_HOST'].'/admin/addAgent',
            'jumpTime'=>2,
        ]);
    }

    /*
     * 代理列表
     */
    public function agentList(Request $request){
        if($request->isMethod('get')){
            $sale = Sale::where('type','=',1)->select('id','name')->get();
            if(!empty($sale)){
                $sale = $sale->toArray();
            }
            $postData = array_filter($request->all());
            $postData['status'] = $request->input('status');
            $list = $this->appLayerExec(Agent::class,'agentList', $postData);
            return view('admin.agent.agent_list',['user'=>1,'client'=>1,'agentListStatus'=>1,'sale'=>$sale,'list'=>$list['res']]);
        }
        /*$sale = Sale::where('type','=',1)->select('id','name')->get()->toArray();
        $postData = array_filter($request->all());
        $postData['status'] = $request->input('status');
        $list = $this->appLayerExec(Agent::class,'agentList', $postData);
//        dd($list);
        return view('admin.agent.agent_list',['user'=>1,'client'=>1,'agentListStatus'=>1,'sale'=>$sale,'list'=>$list['res']]);*/
    }

    public function exportAgentList (Request $request)
    {
        $postData = array_filter($request->all());
        $list = $this->appLayerExec(Agent::class, 'agentListNoPage', $postData);
        $finallData = $list['res'];
        $title = [
            '全称',
            '简称',
            '性质',
            '主营业员',
            '签约时间',
            '过期时间',
            '联系人',
            '联系电话',
            '微信',
            '已有代理'
        ];
        $arr = [];
        //'full_name', 'simple_name', 'agent_type', 'main', 'fix_date', 'phone_name', 'phone', 'weixin'
        foreach ($finallData as $k => $v) {
            $arr[$k]['full_name'] = $v['full_name'];
            $arr[$k]['simple_name'] = $v['simple_name'];
            $arr[$k]['agent_type'] = $v['agent_type'];
            $arr[$k]['main'] = $v['main'];
            $arr[$k]['fix_date'] = $v['fix_date'];
            $arr[$k]['expired_time'] = $v['expired_time'];
            $arr[$k]['phone_name'] = $v['phone_name'];
            $arr[$k]['phone'] = $v['phone'];
            $arr[$k]['weixin'] = $v['weixin'];
            $arr[$k]['users_info_count'] = $v['users_info_count'];
        }

        array_unshift($arr, $title);
        Excel::create('excel', function($excel) use($arr) {

            $excel->sheet('agentList', function ($sheet) use($arr) {
                $sheet->setWidth('A', 40);
                $sheet->fromArray($arr, null, 'A1', false, false);
            });

        })->export('xlsx');
    }


    /*
    * 代理详情
    */
    public function agentDetail($id){
        $postData['id'] = $id;
        $detail = $this->appLayerExec(Agent::class,'agentDetail', $postData);
        return view('admin.agent.agent_detail',['v'=>$detail['res'][0]]);
    }

    /*
    * 代理详情
    */
    public function updateAgent(Request $request,$id){
        if($request->isMethod('get')){
            $agent = \App\Models\Agent\Agent::where('id','=',$id)->get();
            if(!empty($agent)){
                $agent = $agent->toArray();
            }
            $agent[0]['memory_day'] = unserialize($agent[0]['memory_day']);
            return view('admin.agent.update_agent',['v'=>$agent[0],'id'=>$id]);
        }
        $postData = array_filter($request->all());
        $res = $this->appLayerExec(Agent::class,'updateAgent', $postData);
        if($res['code'] == 200){
            return view('admin.jump')->with(['url'=>'http://'.$_SERVER['HTTP_HOST'].'/admin/updateAgent/'.$id]);
        }else{
            return view('admin.jump')->with(['url'=>'http://'.$_SERVER['HTTP_HOST'].'/admin/updateAgent/'.$id,'message'=>'操作失败']);
        }
    }

    /*
    * 根据agent_id查看用户信息
    */
    public function userByAgentId($agent_id){
        $postData['software_id'] = $agent_id;
        $res = $this->appLayerExec(Agent::class,'userByAgentId', $postData);
        return view('admin.agent.user_list',['list'=>$res['res']]);
    }

    /*
     * 处理违约
     */
    public function deal(Request $request,$id,$type){
        if($request->isMethod('get')){
            return view('admin.agent.deal',['id'=>$id,'type'=>$type]);
        }
        $postData = array_filter($request->all());
        $res = $this->appLayerExec(Agent::class,'deal', $postData);
        if($res['code'] == 200){
            flash('处理成功')->success();
            return redirect()->back();
        }
    }

    /*
     * 注销处理
     */
    public function cancle($id,$type){
        $postData['id'] = $id;
        $postData['type'] = $type;
        $res = $this->appLayerExec(Agent::class,'cancle', $postData);
        if($res['code'] == 200){
            return view('admin.jump')->with(['url'=>'http://'.$_SERVER['HTTP_HOST'].'/admin/agentDetail/'.$id]);
        }
    }

    //恢复账号
    public function renew($id){
        $res = \App\Models\Agent\Agent::where('id','=',$id)->update(['status'=>2]);
        if($res){
            return view('admin.jump')->with(['url'=>'http://'.$_SERVER['HTTP_HOST'].'/admin/agentDetail/'.$id]);
        }else{
            return '恢复失败';
        }
    }

    /*
     * 更新协议
     */
    public function updateProtocol(Request $request){
        if ($request->isMethod('get') && $request['type'] == '用户') {
            return view('admin.agent.update_protocol', ['id' => $request['id'], 'type' => $request['type']]);
        }
        if ($request->isMethod('get') && $request['type'] == '代理') {
            return view('admin.agent.update_protocol_agent', ['id' => $request['id'], 'type' => $request['type']]);
        }
        $postData = $request->all();
        if ($postData['type'] == "用户") {
            $signed_time = strtotime($postData['signed_time']);
            if (isset($postData['agreement'])) {
                $fileRes = $this->fileUpload($request, 'agreement');
                if (!$fileRes['status']) {
                    throw_exception('请上传协议');
                }
                $postData['agreement'] = $fileRes['url'];
            }
            $postData['expired_time'] = 0;
            if ($postData['sign_time'] != 4) {
                $postData['expired_time'] = $signed_time + (int)$postData['sign_time'] * 60 * 60 * 24 * 365;
            }
        }
        if ($postData['type'] == "代理") {
            $fix_date = strtotime($postData['fix_date']);
            if (isset($postData['protocol_file'])) {
                $fileRes = $this->fileUpload($request, 'protocol_file');
                if (!$fileRes['status']) {
                    throw_exception('请上传协议');
                }
                $postData['protocol_file'] = $fileRes['url'];
            }
            $postData['expired_time'] = $fix_date + (int)$postData['fix_choose'] * 60 * 60 * 24 * 365;
        }
        $res = $this->appLayerExec(Agent::class,'updateProtocol', $postData);
        if($res['code'] == 200){
            flash('操作成功')->success();
            return redirect()->back();
        }
    }

    public function export()
    {
        $cellData = [
            ['学号','姓名','成绩'],
            ['10001','AAAA','99'],
            ['10002','BBBBB','92'],
            ['10003','CCCCC','95'],
            ['10004','DDDDD','89'],
            ['10005','EEEEE','96'],
        ];
        Excel::create('学生成绩',function($excel) use ($cellData){
            $excel->sheet('score', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });

        })->export('xls');
    }

    public function daoru()
    {
        $filePath = iconv('UTF-8', 'GBK', 'users') . '.xlsx';
        Excel::load($filePath, function($reader) {
            $data = $reader->all();
        });
    }

    public function makeSoftware(){
        for($i=1;$i<=100;$i++){
            $software_id = 'SK'.str_pad($i,5,0,STR_PAD_LEFT);
            $res = Software::insert(['software_id'=>$software_id]);
        }
        if($res){
            return '成功生成';
        }
    }

//    三咖移动端
    public function homePage()
    {
        return view('admin.agent.homePage');
    }

}